import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/pages/home/home/model/device_base_info_resp.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';

class DeviceInfoPage extends ConsumerStatefulWidget {
  const DeviceInfoPage({super.key});

  @override
  ConsumerState<DeviceInfoPage> createState() => _DeviceInfoPageState();
}

class _DeviceInfoPageState extends ConsumerState<DeviceInfoPage> {
  DeviceBaseInfoData baseInfoData = DeviceBaseInfoData();
  final _deviceNameController = TextEditingController();

  _buildList() {
    double descFontSize = 16;
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      child: ListView.separated(
        itemCount: 5,
        shrinkWrap: true,
        itemBuilder: (context, index) {
          switch (index) {
            case 0:
              return GestureDetector(
                onTap: () {
                  // 弹窗输入新的设备名称
                  showDialog(
                      context: context,
                      builder: (context) {
                        return AlertDialog(
                          backgroundColor: Colors.white,
                          surfaceTintColor: Colors.white,
                          title: Text('修改设备名称'),
                          content: TextField(
                            controller: _deviceNameController,
                            decoration: InputDecoration(
                              hintText: '请输入新的设备名称',
                              // 下划线颜色
                              focusedBorder: UnderlineInputBorder(
                                borderSide: BorderSide(
                                  color: AppTheme.themeConfig.primaryColor,
                                ),
                              ),
                            ),
                            // 光标颜色
                            cursorColor: AppTheme.themeConfig.primaryColor,
                            // 长度限制
                            maxLength: 16,
                          ),
                          actions: [
                            TextButton(
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                              child: Text(
                                '取消',
                                style: TextStyle(color: AppTheme.themeConfig.primaryColor),
                              ),
                            ),
                            TextButton(
                              onPressed: () {
                                _modifyDeviceName();
                              },
                              child: Text(
                                '确定',
                                style: TextStyle(color: AppTheme.themeConfig.primaryColor, fontWeight: FontWeight.bold),
                              ),
                            ),
                          ],
                        );
                      });
                },
                child: _buildTableCell('设备名称', baseInfoData.deviceName ?? '', showArrow: true),
              );
            case 1:
              return _buildTableCell('设备号', baseInfoData.imei ?? '');
            case 2:
              return _buildTableCell('设备型号', baseInfoData.model ?? '');
            case 3:
              return _buildTableCell('到期时间', baseInfoData.expiryTime ?? '');
            case 4:
              return _buildTableCell('ICCID', baseInfoData.iccid ?? '');
          }
        },
        separatorBuilder: (context, index) {
          return Divider();
        },
      ),
    );
  }

  _buildTableCell(String title, String desc, {bool showArrow = false}) {
    return Container(
        height: 44,
        padding: EdgeInsets.only(left: 20, right: 20),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              title,
              style: TextStyle(fontSize: 16),
            ),
            Row(
              children: [
                Container(
                  // color: Colors.blue,
                  width: ScreenUtil.getScreenW(context) - 150,
                  alignment: Alignment.centerRight,
                  child: Text(
                    desc,
                    style: TextStyle(
                        fontSize: 16, color: AppTheme.themeConfig.infoTextColor, fontWeight: FontWeight.normal),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                if (showArrow)
                  Icon(
                    Icons.arrow_forward_ios,
                    size: 16,
                    color: AppTheme.themeConfig.infoTextColor,
                  ),
              ],
            ),
          ],
        ));
  }

  void _fetchDeviceInfo() async {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    var res = await get<DeviceBaseInfoResp, DeviceBaseInfoResp>('/device/base/${deviceInfo.imei}',
        decodeType: DeviceBaseInfoResp());
    res.when(
        success: (resp) {
          if (resp.code == 200) {
            setState(() {
              baseInfoData = resp.data!;
            });
          } else {
            ToastUtils.showToast(resp.msg ?? '未查询到设备信息');
          }
        },
        failure: (String msg, int code) {});
  }

  void _modifyDeviceName() async {
    // 校验设备名称，不能为空
    if (_deviceNameController.text.isEmpty) {
      ToastUtils.showToast('设备名称不能为空');
      return;
    }
    var postData = {
      'imei': baseInfoData.imei,
      'deviceName': _deviceNameController.text,
    };
    ToastUtils.showLoading();
    var res = await post<BaseResp, BaseResp>('/device/updateName', data: postData, decodeType: BaseResp());
    res.when(
        success: (resp) {
          ToastUtils.dismissLoading();
          if (resp.code == 200) {
            ToastUtils.showToast('修改成功');
            Navigator.of(context).pop();
            _fetchDeviceInfo();
          } else {
            ToastUtils.showToast(resp.msg ?? '修改失败');
          }
        },
        failure: (String msg, int code) {});
  }

  @override
  void initState() {
    //监听Widget是否绘制完毕
    WidgetsBinding.instance.addPostFrameCallback(_afterLayout);
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  _afterLayout(_) {
    _fetchDeviceInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '设备信息',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      backgroundColor: Color(0xFFF5F5F5),
      body: _buildList(),
    );
  }
}
